package com.llyb.lease.common.main;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class MonitorAspect {

    @Around("@annotation(com.llyb.lease.common.main.MethodMonitor)")
    public Object aroundMonitor(ProceedingJoinPoint proceedingJoinPoint){

        Object retValue = null;

        long start = System.currentTimeMillis();
        long end = 0;
        long costTime = 0;
        String params = null;
        String resultString = null;
        try {
            retValue = proceedingJoinPoint.proceed();
            // 返回输入的形参
            ObjectMapper objectMapper = new ObjectMapper();
            params = objectMapper.writeValueAsString(proceedingJoinPoint.getArgs());

            // 返回方法的结果

            if (retValue!=null) {
                resultString = objectMapper.writeValueAsString(retValue);
            }else {
                resultString=null;
            }

            end = System.currentTimeMillis();
            costTime = end - start;
        } catch (Throwable e) {
            e.printStackTrace();
        }finally {
            log.info("\n方法分析上报中 " +
                    "\n类名方法名:"+proceedingJoinPoint.getTarget().getClass().getName()+"."+proceedingJoinPoint.getSignature().getName()+"()"+
                    "\n执行耗时:"+costTime+"毫秒"+
                    "\n输入参数:"+params+""+
                    "\n返回结果:"+resultString+"" +
                    "\nover");
        }

        return retValue;
    }
}
